<?php
// Register Custom Post Type
function custom_post_type() {

	$labels = array(
		'name'                => _x( 'Soft', 'Post Type General Name', 'text_domain' ),
		'singular_name'       => _x( 'Soft', 'Post Type Singular Name', 'text_domain' ),
		'menu_name'           => __( 'Soft', 'text_domain' ),
		'parent_item_colon'   => __( 'Parent Item:', 'text_domain' ),
		'all_items'           => __( 'Tất cả', 'text_domain' ),
		'view_item'           => __( 'View Item', 'text_domain' ),
		'add_new_item'        => __( 'Add New Item', 'text_domain' ),
		'add_new'             => __( 'Add New', 'text_domain' ),
		'edit_item'           => __( 'Edit Item', 'text_domain' ),
		'update_item'         => __( 'Update Item', 'text_domain' ),
		'search_items'        => __( 'Search Item', 'text_domain' ),
		'not_found'           => __( 'Not found', 'text_domain' ),
		'not_found_in_trash'  => __( 'Not found in Trash', 'text_domain' ),
	);
	$args = array(
		'label'               => __( 'soft', 'text_domain' ),
		'description'         => __( 'Soft', 'text_domain' ),
		'labels'              => $labels,
		'supports'            => array( ),
		'taxonomies'          => array( 'category', 'post_tag', ' publisher', 'license'),
		'hierarchical'        => false,
		'public'              => true,
		'show_ui'             => true,
		'show_in_menu'        => true,
		'show_in_nav_menus'   => true,
		'show_in_admin_bar'   => true,
		'menu_position'       => 5,
		'menu_icon'           => '',
		'can_export'          => true,
		'has_archive'         => true,
		'exclude_from_search' => false,
		'publicly_queryable'  => true,
		'capability_type'     => 'page',
	);
	register_post_type( 'soft', $args );

}

// Hook into the 'init' action
//add_action( 'init', 'custom_post_type', 0 );















// Register Custom Taxonomy
function custom_taxonomy() {

	$labels_man = array(
		'name'                       => _x( 'Nhà xuất bản', 'Taxonomy General Name', 'text_domain' ),
		'singular_name'              => _x( 'publisher', 'Taxonomy Singular Name', 'text_domain' ),
		'menu_name'                  => __( 'Nhà sản xuất', 'text_domain' ),
		'all_items'                  => __( 'All Items', 'text_domain' ),
		'parent_item'                => __( 'Parent Item', 'text_domain' ),
		'parent_item_colon'          => __( 'Parent Item:', 'text_domain' ),
		'new_item_name'              => __( 'New Item Name', 'text_domain' ),
		'add_new_item'               => __( 'Add New Item', 'text_domain' ),
		'edit_item'                  => __( 'Edit Item', 'text_domain' ),
		'update_item'                => __( 'Update Item', 'text_domain' ),
		'separate_items_with_commas' => __( 'Separate items with commas', 'text_domain' ),
		'search_items'               => __( 'Search Items', 'text_domain' ),
		'add_or_remove_items'        => __( 'Add or remove items', 'text_domain' ),
		'choose_from_most_used'      => __( 'Choose from the most used items', 'text_domain' ),
		'not_found'                  => __( 'Not Found', 'text_domain' ),
	);
	$args_man = array(
		'labels'                     => $labels_man,
		'hierarchical'               => true,
		'public'                     => true,
		'show_ui'                    => true,
		'show_admin_column'          => true,
		'show_in_nav_menus'          => true,
		'show_tagcloud'              => true,
	);
	
	$labels_lic = array(
		'name'                       => _x( 'Bản quyền', 'Taxonomy General Name', 'text_domain' ),
		'singular_name'              => _x( 'license', 'Taxonomy Singular Name', 'text_domain' ),
		'menu_name'                  => __( 'Bản quyền', 'text_domain' ),
		'all_items'                  => __( 'All Items', 'text_domain' ),
		'parent_item'                => __( 'Parent Item', 'text_domain' ),
		'parent_item_colon'          => __( 'Parent Item:', 'text_domain' ),
		'new_item_name'              => __( 'New Item Name', 'text_domain' ),
		'add_new_item'               => __( 'Add New Item', 'text_domain' ),
		'edit_item'                  => __( 'Edit Item', 'text_domain' ),
		'update_item'                => __( 'Update Item', 'text_domain' ),
		'separate_items_with_commas' => __( 'Separate items with commas', 'text_domain' ),
		'search_items'               => __( 'Search Items', 'text_domain' ),
		'add_or_remove_items'        => __( 'Add or remove items', 'text_domain' ),
		'choose_from_most_used'      => __( 'Choose from the most used items', 'text_domain' ),
		'not_found'                  => __( 'Not Found', 'text_domain' ),
	);
	$args_lic = array(
		'labels'                     => $labels_lic,
		'hierarchical'               => true,
		'public'                     => true,
		'show_ui'                    => true,
		'show_admin_column'          => true,
		'show_in_nav_menus'          => true,
		'show_tagcloud'              => true,
	);
	
	register_taxonomy( 'license', array( 'post' ), $args_lic );
	register_taxonomy( 'publisher', array( 'post' ), $args_man );

}

// Hook into the 'init' action
add_action( 'init', 'custom_taxonomy', 0 );














//meta box


/**
 * Adds a box to the main column on the Post and Page edit screens.
 */
function myplugin_add_meta_box() {

	$screens = array( 'post');

	foreach ( $screens as $screen ) {

		add_meta_box(
			'myplugin_sectionid',
			__( 'Link download', 'myplugin_textdomain' ),
			'myplugin_meta_box_callback',
			$screen
		);
	}
}
add_action( 'add_meta_boxes', 'myplugin_add_meta_box' );

/**
 * Prints the box content.
 * 
 * @param WP_Post $post The object for the current post/page.
 */
function myplugin_meta_box_callback( $post ) {

	// Add an nonce field so we can check for it later.
	wp_nonce_field( 'myplugin_meta_box', 'myplugin_meta_box_nonce' );

	/*
	 * Use get_post_meta() to retrieve an existing value
	 * from the database and use the value for the form.
	 */
	$values = get_post_meta( $post->ID, 'soft_link_download',true);
	$values = json_decode($values,true);
	echo '<div class="linkdownload_content" id="linkdownload_content"> 
	<ul class="tabs">';
	$i = 0;
	if($values){
	foreach($values as $value) {
		echo '<li id="linkdown_'.$i.'" class="linkdown">
		<label for="link_name_'.$i.'">Link Name: </label>
		<input type="text" id="link_name_'.$i.'" name="link_name[]" class="span6 valid" value="' . esc_attr( $value['link_name'] ).'">
		
		<label for="link_link_'.$i.'">Link Download: </label>
		<input type="text" id="link_link_'.$i.'" name="link_link[]" class="span6 valid" value="' . esc_attr( $value['link_download'] ).'">
		
		<input type="button" class="btn btn-danger remove_link" value="Remove" rel="'.$i.'"></li>';
		
		$i++;
	}
	}
	echo '</ul><input type="button" class="btn add_link" value="Add link download"></div>';
	echo '';
	?>
	<style>
	.linkdown {
		width: 100%;
float: left;
	}
</style>
	<script type="text/javascript">
	 (function($){
	$(function(){
	 $(".add_link").live("click",function(){
			var tid = Math.floor(Math.random()*1000+0);
			var html = '<li id="linkdown_'+tid+'" class="linkdown"><label for="link_name_'+tid+'">Link Name: </label><input type="text" id="link_name_'+tid+'" name="link_name[]" class="span6 valid" value=""><label for="link_link_'+tid+'">Link Download: </label><input type="text" id="link_link_'+tid+'" name="link_link[]" class="span6 valid" value=""><input type="button" class="btn btn-danger remove_link" value="Remove" rel="'+tid+'"></li>';
			
			$("#linkdownload_content >ul").prepend(html);
		});
	$(".remove_link").live("click",function(){
		var link_id = $(this).attr("rel");
		$("#linkdown_"+link_id).remove();
	});
	})
})(jQuery);
</script>
<?php
	
}

/**
 * When the post is saved, saves our custom data.
 *
 * @param int $post_id The ID of the post being saved.
 */
function myplugin_save_meta_box_data( $post_id ) {
	// Check if our nonce is set.
	if ( ! isset( $_POST['myplugin_meta_box_nonce'] ) ) {
		return;
	}

	// Verify that the nonce is valid.
	if ( ! wp_verify_nonce( $_POST['myplugin_meta_box_nonce'], 'myplugin_meta_box' ) ) {
		return;
	}

	// If this is an autosave, our form has not been submitted, so we don't want to do anything.
	if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
		return;
	}

	// Check the user's permissions.
	if ( isset( $_POST['post_type'] ) && 'page' == $_POST['post_type'] ) {

		if ( ! current_user_can( 'edit_page', $post_id ) ) {
			return;
		}

	} else {

		if ( ! current_user_can( 'edit_post', $post_id ) ) {
			return;
		}
	}

	/* OK, its safe for us to save the data now. */

	// Sanitize user input.
	//$my_data = sanitize_text_field( $_POST['myplugin_new_field'] );

	$link_names =  $_POST['link_name'];
	$link_links =  $_POST['link_link'];
	$arr_insert = array();
	for($i=0; $i<count($link_links); $i++){
		$arr_insert[$i] = array(
			'link_name'=>$link_names[$i],
			'link_download'=>$link_links[$i],
		);
	}
	//serialize(
	//delete_post_meta( $post_id, '_my_meta_value_key');   
	//foreach ($datas as $data){
		update_post_meta($post_id, 'soft_link_download', json_encode($arr_insert));
	//}

}
add_action( 'save_post', 'myplugin_save_meta_box_data' );














function pippin_add_taxonomy_filters() {
	global $typenow;
 
	// an array of all the taxonomyies you want to display. Use the taxonomy name or slug
	$taxonomies = array('publisher');
 
	// must set this to the post type you want the filter(s) displayed on
	if( $typenow == 'softx' ){
 
		foreach ($taxonomies as $tax_slug) {
			$tax_obj = get_taxonomy($tax_slug);
			$tax_name = $tax_obj->labels->name;
			$terms = get_terms($tax_slug);
			if(count($terms) > 0) {
				echo "<select name='$tax_slug' id='$tax_slug' class='postform'>";
				echo "<option value=''>Show All $tax_name</option>";
				foreach ($terms as $term) { 
					echo '<option value='. $term->slug, $_GET[$tax_slug] == $term->slug ? ' selected="selected"' : '','>' . $term->name .' (' . $term->count .')</option>'; 
				}
				echo "</select>";
			}
		}
	}
}
add_action( 'restrict_manage_posts', 'pippin_add_taxonomy_filters' );


//http://us3.php.net/manual/en/function.serialize.php
add_action('add_meta_boxes', 'wpds_media_meta_box');
add_action('save_post','save_softicon');

function wpds_media_meta_box() {
    // change 'post' to any custom post type as per scenario
    add_meta_box('additional_images', 'Icon', 'soft_icon', 'post', 'normal');
    add_meta_box('soft_title', 'Title Description', 'soft_title_description', 'post', 'normal');
    add_meta_box('soft_filesize', 'File Size', 'soft_filesize', 'post', 'normal');
    add_meta_box('soft_version', 'Version', 'soft_version', 'post', 'normal');
    add_meta_box('soft_requirements_os', 'Requirements OS', 'soft_requirements_os', 'post', 'normal');
}

function soft_title_description($post) {
	echo '<input id="" class="" name="soft_title_description" type="text" value="'.get_post_meta($post->ID,'soft_title_description',true).'" />';
}
function soft_filesize($post) {
	echo '<input id="" class="" name="soft_filesize" type="text" value="'.get_post_meta($post->ID,'soft_filesize',true).'" />';
}
function soft_version($post) {
	echo '<input id="" class="" name="soft_version" type="text" value="'.get_post_meta($post->ID,'soft_version',true).'" />';
}
function soft_requirements_os($post) {
	echo '<input id="" class="" name="soft_requirements_os" type="text" value="'.get_post_meta($post->ID,'soft_requirements_os',true).'" />';
}

function soft_icon($post) {
     
    echo '<table>';
     
        echo  '<tr valign="top">' ;
        echo  '<td width="50">' ;
		if(has_icon_image($post->ID) )
                echo '<a href="'.the_icon_image_url($post->ID).'"  target="_blank"><img src="'.the_icon_image_url($post->ID,array(30,30)).'" height=30 /></a>';
        echo '</td>';
        echo '<td valign=top ><input id="add_img_field" type="text" size="36" name="soft_icon'.'" value="'.get_post_meta($post->ID,'soft_icon',true).'" />
        <input id="soft_icon'.'" class="upload_buttons" type="button" value="Upload/Select" /></td>';
        
       echo  '</tr>';
    
    echo '
        <tr><td colspan="4">You can specify an image URL or an attachment ID through Upload/Select button</td></tr>
    </table>';
    ?>
    <script type="text/javascript">
        jQuery(document).ready(function() {
            var formfieldID = '';
            var wpds_orig_send_to_editor = window.send_to_editor;
            jQuery('.upload_buttons').click(function() {
                formfieldID = 'add_img_field';
                tb_show('', 'media-upload.php?type=image&amp;TB_iframe=true');
                 
                window.send_to_editor = function(html) {
                    //attachmentID = html.match(/wp-image-([0-9]+)/);
					attachmentID = jQuery(html).find('img').attr('src');
                    if(attachmentID)
                        //pasteValue = attachmentID[1];
                        pasteValue = attachmentID;
                    else
                        pasteValue = jQuery(html).filter('img').attr('src');
 
                    jQuery('#'+formfieldID).val(pasteValue);
                    tb_remove();
                    window.send_to_editor = wpds_orig_send_to_editor;
                }
                return false;
            });
 
        });
    </script>
    <?php
}
 
function save_softicon($post_id) {
 
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)
        return;
 
    if (wp_is_post_revision($post_id) || wp_is_post_autosave($post_id))
        return;
	if(isset($_POST['soft_icon']))
		update_post_meta($post_id, 'soft_icon', $_POST['soft_icon']);
		
    if(isset($_POST['soft_title_description']))
		update_post_meta($post_id, 'soft_title_description', $_POST['soft_title_description']);
	if(isset($_POST['soft_filesize']))
		update_post_meta($post_id, 'soft_filesize', $_POST['soft_filesize']);
    if(isset($_POST['soft_version']))
		update_post_meta($post_id, 'soft_version', $_POST['soft_version']);
    if(isset($_POST['soft_requirements_os']))
		update_post_meta($post_id, 'soft_requirements_os', $_POST['soft_requirements_os']);
    
}

function has_icon_image($post_id) {
    
    $meta = get_post_meta($post_id,'soft_icon', true);
    if(empty($meta))    return false;
    return true;
}

function the_icon_image_url($post_id,  $size='post-thumbnail') {
    $meta = get_post_meta($post_id,'soft_icon', true);
    if(empty($meta))    return false;
    if(is_numeric($meta)){
        $image = wp_get_attachment_image_src($meta, $size);
        if(!empty($image))
            return $image[0];
        return false;
    }
    else{
        return $meta;
    }
}



function get_the_publisher_link(){
$terms= get_the_terms(get_the_ID(), 'publisher' );
if(!$terms)
	return '';
	foreach($terms as $term){
		return get_term_link($term->slug, 'publisher' );
	}
}

function get_the_publisher_name(){
$terms= get_the_terms(get_the_ID(), 'publisher' );
if(!$terms)
	return '';
	foreach($terms as $term){
		return $term->name;
	}
}

function get_the_license_name(){
$terms= get_the_terms(get_the_ID(), 'license' );
if(!$terms)
	return '';
	foreach($terms as $term){
		return $term->name;
	}
}

function get_the_license_slug(){
$terms= get_the_terms(get_the_ID(), 'license' );
if(!$terms)
	return '';
	foreach($terms as $term){
		return $term->slug;
	}
}

function get_the_license_link(){
$terms= get_the_terms(get_the_ID(), 'license' );
if(!$terms)
	return '';
	foreach($terms as $term){
		return get_term_link($term->slug, 'license' );
	}
}

function get_the_count_download(){
	if(function_exists('the_views')) { the_views(); }
}
if ( function_exists( 'add_theme_support' ) ) {
       add_image_size('index-hot-thumb', 180, 190, true );
}

function get_post_by_slug($post_slug) {
	$posts = get_posts( array( 'name' => $post_slug ) );
	if( count($posts) )
	{
		return $posts;
	}

}

function get_root_category($cat_id){
$this_cat = get_category($cat_id);
if($this_cat->category_parent!=0){
    do{
        $this_cat = get_category($this_cat->category_parent);
    }while($this_cat->category_parent!=0);
}
	return $this_cat;
}

function _import_photo( $postid, $photo_url ) {
	$post = get_post( $postid );
	if( empty( $post ) )
		return false;

	if( !class_exists( 'WP_Http' ) )
	  include_once( ABSPATH . WPINC. '/class-http.php' );

	$photo = new WP_Http();
	$photo = $photo->request($photo_url );
	if( $photo['response']['code'] != 200 )
		return false;

	$attachment = wp_upload_bits(basename($photo_url), null, $photo['body'], date("Y-m", strtotime( $photo['headers']['last-modified'] ) ) );
	if( !empty( $attachment['error'] ) )
		return false;

	$filetype = wp_check_filetype( basename( $attachment['file'] ), null );

	$postinfo = array(
		'post_mime_type'	=> $filetype['type'],
		'post_title'		=> $post->post_title,
		'post_content'		=> '',
		'post_status'		=> 'inherit',
	);
	$filename = $attachment['file'];
	$attach_id = wp_insert_attachment( $postinfo, $filename, $postid );
	
	if( !function_exists( 'wp_generate_attachment_data' ) )
		require_once(ABSPATH . "wp-admin" . '/includes/image.php');
	$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
	wp_update_attachment_metadata( $attach_id,  $attach_data );
	return $attach_id;
}

function get_level($category, &$level = 0)
{
    if ($category->category_parent == 0) {
        return $level;
    } else {
        $level++;
        $category = get_category($category->category_parent);
        get_level($category, $level);
    }
}